package fragment;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import activity.driverrepair.DriverRepair;
import activity.personal.ActivityRepair;
import adapter.order_adapter.OrdersAdapter;
import base.BaseFragment;
import base.MyApplcation;
import bean.LuntanForumItemBean;
import bean.order_bean.WeixiuKeJieBen;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import presenter.SysTemPresenter;
import presenter.UserPresenter;
import util.utls.BasePtr;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.OrderBtnSed;
import util.utls.SPUtils;
import util.volley.ResultEntity;

/**
 * 可接订单
 */
public class OrdersFragemnt extends BaseFragment implements Observer, OrderBtnSed {
    private ListView listview;
    private OrdersAdapter ordersAdapter;
    SysTemPresenter presenter;
    SysTemPresenter presenter01;
    LuntanForumItemBean bean;
    LinearLayout linJiNeng;
    TextView tvGetjineng;

    Button btnsends;
    private LocationClient locClient;
    double dblng;
    double dblat;
    private RelativeLayout reyoutMap;
    PtrFrameLayout commend_anchor_ptr;
    LinearLayout didngdane;
    private static final int BAIDU_READ_PHONE_STATE = 100;
    int pageNum=1;
    int pageSize=10;
    WeixiuKeJieBen ben;
    List<WeixiuKeJieBen.InfoBean> listBean=new ArrayList<>();

    String versionNow;//版本号
    UserPresenter userPresenter;

    String uid;

    @Override
    public int initView() {
        return R.layout.fragment_orders;
    }

    @Override
    public void onMyActivityCreated() {
        uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
        BasePtr.setPagedPtrStyle(commend_anchor_ptr);//设置上拉下拉刷新
        locClient = new LocationClient(getActivity().getApplicationContext());
        locClient.registerLocationListener(new MyLocationListener());
        versionNow = getAppVersionName(getActivity());
        userPresenter=new UserPresenter(this);

        isCameraPermission(getActivity(),1);
        InitLocation();

        presenter = new SysTemPresenter(this);
        presenter01=new SysTemPresenter(this);
        bean = new LuntanForumItemBean();
        showProgressDialog("数据加载中...", true);
        presenter.onGetJineng(uid);

        ben = new WeixiuKeJieBen();

        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {//刷新的监听事件
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                pageNum++;
                if(dblat>0){
                    presenter01.onWeixiuJie(uid,pageNum+"", pageSize+"", dblng + "", dblat + "","1");
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                InitLocation();
                if(dblat>0){
                    presenter01.onWeixiuJie(uid, pageNum+"", pageSize+"", dblng + "", dblat + "","1");
                }
            }
        });
        commend_anchor_ptr.autoRefresh();

        // 广播发过来有新的订单  刷新界面
        IntentFilter filter1 = new IntentFilter("weixiu");
        getActivity().registerReceiver(shuaxinReceiver, filter1);

        //登录的广播
        IntentFilter filter = new IntentFilter("chaingLogin");
        getActivity().registerReceiver(loginReceiver, filter);

    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplcation.ctx, null, Const.ID, "");
            presenter01.onWeixiuJie(uid, pageNum+"", pageSize+"", dblng + "", dblat + "","1");
        };
    };

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public static boolean isCameraPermission(Activity context, int requestCode){
        if (Build.VERSION.SDK_INT >= 23) {
            int aPermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE);
            int bPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            int cPermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION);
            int dPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int ePermission = ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (aPermission != PackageManager.PERMISSION_GRANTED || bPermission!= PackageManager.PERMISSION_GRANTED || cPermission!= PackageManager.PERMISSION_GRANTED|| dPermission!= PackageManager.PERMISSION_GRANTED|| ePermission!= PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS,requestCode);
                return false;
            }
        }
        return true;
    }
    BroadcastReceiver shuaxinReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            presenter01.onWeixiuJie(uid, pageNum+"", "20", dblng + "", dblat + "","1");
        };
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(shuaxinReceiver);
        getActivity().unregisterReceiver(loginReceiver);

    }

    public static void phoneCall(String result) {

        Log.e("Activity中的定位信息:", result);
//        locInfo.setText(result);
    }

    public void onStop() {
        // TODO Auto-generated method stub
        locClient.stop();
        super.onStop();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }
    private void InitLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        locClient.setLocOption(option);
        locClient.start();
    }

    @Override
    public void onBtnSend(View v) {


    }

    @Override
    public void onTvMap(View v) {

    }

    /**
     * 实现实位回调监听
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            double mLat1 = 30.3154340000;
            // point1纬度
            double mLon1 = 120.3415480000; // point1经度
            double lngs = 120.3826130000;// point2纬度
            double lats = 30.3171010000;// point2经度
            dblng = location.getLongitude();//纬度
            dblat = location.getLatitude();//精度
         //   double distance = BiaduMaps.GPSLng(lats, mLon1, mLat1, lngs);

            SPUtils.put(getActivity(), null,
                    Const.LAT, location.getLatitude());
            SPUtils.put(getActivity(), null,
                    Const.LNG, location.getLongitude());
            if(dblat>0){
                presenter01.onWeixiuJie(uid, pageNum+"", pageSize+"", dblng + "", dblat + "","1");
                listBean=new ArrayList<WeixiuKeJieBen.InfoBean>();
                ordersAdapter = new OrdersAdapter(getActivity(), listBean, dblng, dblat, OrdersFragemnt.this);
                listview.setAdapter(ordersAdapter);
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (getId()) {
            case R.id.tvGetjineng:
                intent = new Intent(getActivity(), ActivityRepair.class);
                startActivity(intent);
                break;
        }

    }

    @Override
    public void update(Observable observable, Object data) {
        commend_anchor_ptr.refreshComplete();//设置刷新完成
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == presenter.GetJineng_success) {

                bean = (LuntanForumItemBean) entity.getData();
                if (bean.getUser_skills().size() <= 0) {
                    linJiNeng.setVisibility(View.VISIBLE);
                    listview.setVisibility(View.GONE);
                    commend_anchor_ptr.setVisibility(View.GONE);
                    ByAlert.alert("您还未添加技能");
                    didngdane.setVisibility(View.GONE);
                    Intent intent = new Intent(getActivity(), ActivityRepair.class);
                    startActivity(intent);

                } else {

                    linJiNeng.setVisibility(View.GONE);
                    listview.setVisibility(View.VISIBLE);
                    commend_anchor_ptr.setVisibility(View.VISIBLE);
                }
            } else if (entity.getEventType() == presenter.WeiXiuKejie_success) {
                if(pageNum==1){
                    listBean.clear();
                }
                commend_anchor_ptr.refreshComplete();//设置刷新完成

                ben = (WeixiuKeJieBen) entity.getData();
                listBean.addAll(ben.getList());
                if (listBean.size() <= 0) {
                    if(pageNum==1){
                        linJiNeng.setVisibility(View.GONE);
                        listview.setVisibility(View.GONE);
                        didngdane.setVisibility(View.VISIBLE);
                        listview.setVisibility(View.GONE);
                        commend_anchor_ptr.setVisibility(View.GONE);
                        DriverRepair.onSetFragment().viewPager.setCurrentItem(1);//如果有订单跳转到订单里面
                    }

                } else {
                    ordersAdapter.notifyDataSetChanged();
                    listview.invalidate();
                    didngdane.setVisibility(View.GONE);
                    linJiNeng.setVisibility(View.GONE);
                    didngdane.setVisibility(View.GONE);
                    listview.setVisibility(View.VISIBLE);

                    commend_anchor_ptr.setVisibility(View.VISIBLE);
                }
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }
}
